import { Select, Space, Table, Input, Button, message, Form, Modal, Cascader } from 'antd';
import { SettingOutlined } from '@ant-design/icons';
import React, { useState, useEffect } from 'react';
import { useNavigate } from "react-router-dom"
import './index.scss';
import {
  getAllFloor, fetchData, addFloor, delFloor, change, addMsg,
  getTrend, searchTrend, addTrend, editTrend, deleteTrend
} from '@/utils/hsyHttp/hsyhttp.jsx'


import { ExclamationCircleFilled } from "@ant-design/icons";

// 头部
import PageName from '../../../../components/PageName/index.jsx';

// 日期格式转换
import { parseTime } from '../../../../utils/date.jsx';

const { confirm } = Modal;
const App = () => {
  const option = [
    {
      value: '楼盘编号',
      label: '楼盘编号',
    },
    {
      value: '楼盘名称',
      label: '楼盘名称',
    },
  ]
  const options = [
    {
      value: '海淀',
      label: '海淀',
      children: [
        {
          value: '西北旺',
          label: '西北旺',
        },
        {
          value: '安贞',
          label: '安贞',
        },
        {
          value: '北沙滩',
          label: '北沙滩',
        },
        {
          value: '北工大',
          label: '北工大',
        },
        {
          value: '朝阳门',
          label: '朝阳门',
        },
      ],
    },
    {
      value: '丰台',
      label: '丰台',
      children: [
        {
          value: '西北旺',
          label: '西北旺',
        },
        {
          value: '安贞',
          label: '安贞',
        },
        {
          value: '北沙滩',
          label: '北沙滩',
        },
        {
          value: '北工大',
          label: '北工大',
        },
        {
          value: '朝阳门',
          label: '朝阳门',
        },
      ],
    },
  ];
  const onChange = (value) => {
    console.log(value);
  };
  //路由跳转
  const navigate = useNavigate()
  // const [editId, setEditId] = useState(1)
  const [messageApi, contextHolder] = message.useMessage();
  const success = (content) => {
    messageApi.open({
      type: "success",
      content,
    });
  };
  //表单
  const [form] = Form.useForm();
  const formRef = React.useRef(null);
  //分页
  const [total, setTotal] = useState(1)
  // 页数
  const [currentPage, setCurrentPage] = useState(1)

  // 页面改变
  const pageChange = (page) => {
    setCurrentPage(page.current);
  }


  //添加
  const addFloor = () => {
    navigate('/home/AddFloor')
  }
  //编辑
  const EidFloor = (c_id) => {
    console.log('编辑', c_id);
    navigate('/home/EditPersonalUser', { state: { c_id } })
  }
  //搜索
  const searchFloorData = (params) => {
    console.log(params);
    console.log(params.c_area == '全部');
    if (params.c_area == '' || params.c_area == '全部') {
      params.c_area = ''
    } else {
      params.c_area = params.c_area[0] + "-" + params.c_area[1]
    }
    if (params.s_state == '全部') {
      params.s_state = ''
    }
    if (params.c_state == '全部') {
      params.c_state = ''
    }
    if (params.price == '') {
      params.price = []
    }
    if (params.c_name == '') {
      params.c_name = ''
    }
    console.log(params);
    fetchData(params).then(res => {
      let tableData = res.data
      setData(tableData)
      setTotal(tableData.length)
      message.success(res.msg)
    })
  };
  //表格数据
  useEffect(() => {
    getFloorData()
  }, [])
  //获取数据
  const [data, setData] = useState([])
  const getFloorData = () => {
    getAllFloor().then((res) => {
      let tableData = res.data
      setData(tableData)
      setTotal(tableData.length)
    })
  }


  //上下线
  const [buttonText, setButtonText] = useState('');
  const showConfirm = (title, record) => {
    confirm({
      title,
      icon: <ExclamationCircleFilled />,
      content: "",
      okText: "确认",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        change({ c_id: record.c_id, c_state: record.c_state }).then((res) => {
          if (buttonText === "下线") {
            setButtonText('下线')
          }
          getFloorData()
          success(res.msg);
        });
      },
    });
  };
  const showConf = (title, record) => {
    confirm({
      title,
      icon: <ExclamationCircleFilled />,
      content: "",
      okText: "确认",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        change({ c_id: record.c_id, c_state: record.c_state }).then((res) => {
          if (buttonText === "上线") {
            setButtonText('上线')
          }
          getFloorData()
          success(res.msg);
        });
      },
    });
  };
  //删除
  const showDelete = (title, record) => {
    confirm({
      title,
      icon: <ExclamationCircleFilled />,
      content: "",
      okText: "确认",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        delFloor({ c_id: record.c_id }).then((res) => {
          getFloorData()
          success(res.msg);
        });
      },
    });
  };
  //表格
  const columns = [
    {
      title: '编号',
      dataIndex: 'c_id',
      key: 'c_id',
      render: (text, record, index) => index + (currentPage - 1) * 5 + 1
    },
    {
      title: '封面图',
      dataIndex: 'c_img',
      key: 'c_img',
      align: 'center',
      render: (_, { c_img }) => {
        return (
          <img src={'/api' + c_img} style={{ height: '50px' }}></img>
        )
      }
    },
    {
      title: '楼盘名称',
      dataIndex: 'c_name',
      key: 'c_name'
    },
    {
      title: '区域',
      dataIndex: 'c_area',
      key: 'c_area',
    },
    {
      title: '均价',
      dataIndex: 'c_price',
      key: 'c_price',
    },
    {
      title: '状态',
      key: 'c_state',
      dataIndex: 'c_state',
      // render: (_, { c_state }) => (
      //   <>
      //     {c_state.map((tag) => {
      //       let color = tag.length > 5 ? 'geekblue' : 'green';
      //       if (tag === 'loser') {
      //         color = 'volcano';
      //       }
      //       return (
      //         <Tag color={color} key={tag}>
      //           {tag.toUpperCase()}
      //         </Tag>
      //       );
      //     })}
      //   </>
      // ),
    },
    {
      title: '创建人',
      dataIndex: 'c_admin',
      key: 'c_admin',
    },
    {
      title: '创建时间',
      dataIndex: 'c_time',
      key: 'c_time',
      render: (_, { c_time }) => {
        return parseTime(c_time, '{y}-{m}-{d} {h}:{i}:{s}')
      }
    },
    {
      title: '浏览量',
      dataIndex: 'c_property',
      key: 'c_property',
    },

    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => EidFloor(record.c_id)}>编辑</a>
          <a onClick={() => {
            showConfirm("你确定下线吗?", record);
          }}>下线</a>
          <a onClick={() => {
            showConf("你确定上线吗?", record);
          }}>上线</a>
          <a onClick={() => {
            showDelete("你确定删除吗?", record);
          }}>删除</a>

        </Space>
      ),
    },
  ];

  return (
    <div>
          {contextHolder}
      <PageName name={'新房列表'} />
      <Form
        colon={false}
        form={form}
        layout='inline'
        ref={formRef}
        onFinish={searchFloorData}
        style={{
          marginTop: '10px',
          display: 'flex',
          alignItems: 'center',
          lineHeight: '50px'
        }}
        initialValues={{
          c_area: '全部',
          s_state: '全部',
          c_state: '全部',
          price1: '',
          price2:'',
          createName: '',
          c_name: ''
        }}
      >
        <Form.Item label="区域" name="c_area">
          <Cascader options={options} onChange={onChange} />
        </Form.Item>
        <Form.Item label="销售状态" name="s_state">
          <Select
            showSearch
            optionFilterProp="children"
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={[
              {
                value: '全部',
                label: '全部',
              },
              {
                value: '待售',
                label: '待售',
              },
              {
                value: '在售',
                label: '在售',
              },
              {
                value: '售完',
                label: '售完',
              },
            ]}
          />
        </Form.Item>
        <Form.Item label="楼盘状态" name="c_state" >
          <Select
            showSearch
            optionFilterProp="children"
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={[
              {
                value: '全部',
                label: '全部',
              },
              {
                value: '上线',
                label: '上线',
              },
              {
                value: '下线',
                label: '下线',
              },
              {
                value: '推荐',
                label: '推荐',
              },
            ]}
          />
        </Form.Item>
        <Form.Item label="均价" name="price1">
          <Input placeholder="请输入价格" />
        </Form.Item>
        -
        <Form.Item name="price2" label=" ">
          <Input placeholder="请输入价格" />
        </Form.Item>

        <Form.Item label="创建人" name="createName">
          <Input placeholder="请输入创建人" />
        </Form.Item>

        <Form.Item name="c_name" label='楼盘名称'>
          <Input />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">搜索</Button>

          <Button style={{ marginLeft: '10px' }}>清空</Button>
        </Form.Item>
      </Form>
      <Button type="primary" onClick={() => addFloor()} style={{ margin: '20px 0px' }}>添加</Button>


      <Table className={"table"} columns={columns} dataSource={data} rowKey={record => record.c_id}
        pagination={{
          defaultCurrent: 1, total, defaultPageSize: 5, hideOnSinglePage: true
        }} current={currentPage} onChange={pageChange} />

    </div>

  );

};
export default App;